﻿/*
* 命名空间: Service.Library
*
* 功 能： Windows服务帮助类
*
* 类 名： WindowsWorkerClient
*
* Version   变更日期            负责人     变更内容
* ─────────────────────────────────────────────────
* V1.0.1    2020/5/18 13:25:09 	罗维    创建
* ─────────────────────────────────────────────────
*
* Copyright (c) 2020 ZHDL Corporation. All rights reserved.
*/
using Microsoft.Win32;
using System;
using System.Configuration.Install;
using System.Diagnostics;
using System.Reflection;
using System.ServiceProcess;
using System.Text;

namespace Service.Library
{
    /// <summary>
    /// Windows服务帮助类
    /// </summary>
    public class WindowsWorkerClient
    {
        /// <summary>
        /// 获取配置
        /// </summary>
        public WindowsServiceInfo Config { get; private set; }

        /// <summary>
        /// 不公开默认构造函数，请通过InitZipService来创建实例
        /// </summary>
        private WindowsWorkerClient() { }

        /// <summary>
        /// 初始化服务
        /// </summary>
        /// <param name="config">配置对象</param>
        /// <returns>当前压缩服务</returns>
        public static WindowsWorkerClient InitService(WindowsServiceInfo config)
        {
            WindowsWorkerClient ser = new WindowsWorkerClient();
            ser.Config = config;
            return ser;
        }


        /// <summary>
        /// 判断服务是否已经存在
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <returns>bool</returns>
        public bool ServiceIsExisted()
        {
            try
            {
                ServiceController[] services = ServiceController.GetServices();
                foreach (ServiceController s in services)
                {
                    if (s.ServiceName == Config.ServiceName)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return false;
        }

        /// <summary>
        /// 安装服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultInfo InstallService()
        {
            ServiceResultInfo result = new ServiceResultInfo();
            try
            {
                if (ServiceIsExisted())
                {
                    result.Success = false;
                    result.Msg = "服务已经存在！";
                }
                else
                {
                    string[] cmdline = { };

#if (NETSTANDARD2_0 || NETCOREAPP2_2)
                        Console.WriteLine("Target framework: NETSTANDARD2_0 NETCOREAPP2_2");
#else
                    //TransactedInstaller transactedInstaller = new TransactedInstaller();
                    //AssemblyInstaller assemblyInstaller = new AssemblyInstaller(Config.PhysicalPath + "\\" + Config.ExeFile, cmdline);
                    //assemblyInstaller.UseNewContext = true;
                    //transactedInstaller.Installers.Add(assemblyInstaller);
                    //transactedInstaller.Install(new System.Collections.Hashtable());
#endif




                    result.Msg = "安装成功！";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;

        }

        /// <summary>
        /// 运行服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultInfo RunningService()
        {
            ServiceResultInfo result = new ServiceResultInfo();
            try
            {
                if (!ServiceIsExisted())
                {
                    result.Success = false;
                    result.Msg = "服务不存在！";
                }
                else
                {
                    ServiceController service = new ServiceController(Config.ServiceName);
                    if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
                    {
                        if (Config.DomainPort.Length > 0)
                        {
                            string[] paramsString = Config.DomainPort.Split(new char[] { ',' });
                            service.Start(paramsString);
                        }
                        else
                        {
                            service.Start();
                        }
                    }
                    result.Msg = "运行服务成功！";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <returns></returns>
        public ServiceResultInfo StopService()
        {
            ServiceResultInfo result = new ServiceResultInfo();
            try
            {
                if (!ServiceIsExisted())
                {
                    result.Success = false;
                    result.Msg = "服务不存在！";
                }
                ServiceController service = new ServiceController(Config.ServiceName);
                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                    service.Dispose();
                    result.Msg = "停止服务成功！";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// 卸载服务
        /// </summary>
        public ServiceResultInfo UninstallService()
        {
            ServiceResultInfo result = new ServiceResultInfo();
            try
            {
                if (!ServiceIsExisted())
                {
                    result.Success = false;
                    result.Msg = "服务不存在！";
                }
                string[] cmdline = { };

#if (NETSTANDARD2_0 || NETCOREAPP2_2)
                                        Console.WriteLine("Target framework: NETSTANDARD2_0 NETCOREAPP2_2");
#else
                TransactedInstaller transactedInstaller = new TransactedInstaller();
                AssemblyInstaller assemblyInstaller = new AssemblyInstaller(Config.PhysicalPath + "\\" + Config.ExeFile, cmdline);
                transactedInstaller.Installers.Add(assemblyInstaller);
                transactedInstaller.Uninstall(null);
#endif




                result.Msg = "卸载服务成功！";
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        /// <summary>
        /// 查看服务运行情况
        /// </summary>
        /// <param name="serviceFileName"></param>
        /// <returns></returns>
        public  ServiceResultInfo ViewService()
        {
            ServiceResultInfo result = new ServiceResultInfo();
            try
            {
                if (string.IsNullOrEmpty(Config.ServiceName))
                {
                    result.Success = true;
                    result.Msg = "指定文件不是Windows服务！";
                    result.Code = 10;
                    return result;
                }
                if (!ServiceIsExisted())
                {
                    result.Success = true;
                    result.Msg = "服务不存在！";
                    result.Code = 11;
                }
                else
                {
                    ServiceController service = new ServiceController(Config.ServiceName);
                    result.Success = true;
                    switch (service.Status)
                    {
                        case ServiceControllerStatus.ContinuePending:
                            result.Msg = "服务继续处于挂起状态！";
                            result.Code = 5;
                            break;
                        case ServiceControllerStatus.Paused:
                            result.Msg = "服务已暂停！";
                            result.Code = 7;
                            break;
                        case ServiceControllerStatus.PausePending:
                            result.Msg = "服务暂停处于挂起状态！";
                            result.Code = 6;
                            break;
                        case ServiceControllerStatus.Running:
                            result.Msg = "该服务正在运行！";
                            result.Code = 4;
                            break;
                        case ServiceControllerStatus.StartPending:
                            result.Msg = "服务正在启动！";
                            result.Code = 2;
                            break;
                        case ServiceControllerStatus.Stopped:
                            result.Msg = "服务未运行！";
                            result.Code = 1;
                            break;
                        case ServiceControllerStatus.StopPending:
                            result.Msg = "服务正在停止！";
                            result.Code = 3;
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.Message;
            }
            return result;
        }


        //private bool AdminRestartApp(string filePath, string[] args)
        //{
        //    if (!IsAdmin())
        //    {
        //        Console.WriteLine("重新已管理员启动" + filePath);
        //        ProcessStartInfo startInfo = new ProcessStartInfo
        //        {
        //            UseShellExecute = true,
        //            Arguments = string.Join(" ", args),
        //            WorkingDirectory = Environment.CurrentDirectory,
        //            FileName = filePath,
        //            Verb = "runas"
        //        };
        //        try
        //        {
        //            Process.Start(startInfo);
        //        }
        //        catch (Exception ex)
        //        {
        //            Console.WriteLine($"重新已管理员启动失败：{ex}");
        //        }
        //        return false;
        //    }
        //    return true;
        //}
        ///// <summary>
        ///// 判断是否是处于Administrator下允许
        ///// </summary>
        ///// <returns></returns>
        //private bool IsAdmin()
        //{
        //    using (System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent())
        //    {
        //        System.Security.Principal.WindowsPrincipal wp = new System.Security.Principal.WindowsPrincipal(wi);
        //        return wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        //    }
        //}
    }
}
